import React, { Component } from 'react';
import AddTodo from './todoListDemo/AddTodo'
import TodoList from './todoListDemo/TodoList'
import Footer from './todoListDemo/Footer'


class App extends Component {
  constructor (props) {
    super(props)
    this.state = {
      lists: [],
      filter: 'all'
    }
    this.nextListId = 0
  }
  render () {
    const lists = this.getVisibleLists()
    const {filter } = this.props
    return (
      <div>
        <AddTodo addList={this.addList}></AddTodo>
        <TodoList toggleClick={this.toggleClick} list={lists}></TodoList>
        <Footer filter={filter} setVisibleLists={this.setVisibleLists}></Footer>
      </div>
    )
  }

  // 数组筛选过滤
  getVisibleLists = () => {
    const currentFilter = this.state.filter
    return this.state.lists.filter(item => {
      if (currentFilter === 'active') {
        return !item.completed
      } else if (currentFilter === 'completed') {
        return item.completed
      } else {
        return true
      }
    })
  }
  // 数据添加
  addList = (text) => {
    const newList = {
      id: this.nextListId++,
      text,
      completed: false
    }
    const newLists = [newList, ...this.state.lists]
    this.setState({
      lists: newLists
    })
  }
  // 数据筛选底部
  setVisibleLists = filter => {
    this.setState({
      filter
    })
  }
  // 点击单项切换状态
  toggleClick = id => {
    const newLists = this.state.lists.map(item => {
      return item.id === id ? {...item, completed: !item.completed} : item
    })
    this.setState({
      lists: newLists
    })
  }
}
export default App;
